package com.decent.ejfadmin.utils;


import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前IP
 *
 * @author tang
 */
public class Ip {

    public static String getIp() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getHeader("X-Real-IP");
        } catch (Exception ex) {
            return "";
        }
    }

    public static String getMemberSystemIp() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getRemoteAddr();
        } catch (Exception ex) {
            return "";
        }
    }

    public static String getUserIp() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getHeader("USER-IP");
        } catch (Exception ex) {
            return "";
        }
    }

    /**
     * 验证用户IP是否合法
     *
     * @param ips    数据库绑定IP
     * @param userIp 用户当前IP
     */
    public static boolean verify(String ips, String userIp) {
        boolean fag = false;
        if (StringUtils.isNotBlank(ips)) {
            String[] tempIp = ips.split(",");
            for (String ip : tempIp) {
                if (ip != null && ip.trim().equals(userIp)) {
                    fag = true;
                    break;
                }
            }
        } else {
            fag = true;
        }
        return fag;
    }
}